﻿using System.Collections.Generic;
using System.Web.Mvc;
using JoelAbrahamsson.Web.Common.HtmlFiltering;

namespace JoelAbrahamsson.Web.Common
{
    public static class HtmlHelperExtensions
    {
        private static HtmlFilter _htmlFilter;
        
        public static string FilterHtml(this HtmlHelper helper, string html)
        {
            if(_htmlFilter == null)
            {
                Dictionary<string, IHtmlTagReplacer> allowedTagReplacements = new Dictionary<string, IHtmlTagReplacer>();
                allowedTagReplacements.Add("b", new SameTagReplacer());
                allowedTagReplacements.Add("em", new SameTagReplacer());
                allowedTagReplacements.Add("quote", new QuoteTagReplacer());
                allowedTagReplacements.Add("code", new CodeTagReplacer());
                allowedTagReplacements.Add("c-sharp-code", new CodeTagReplacer { BrushName = "c-sharp" });
                allowedTagReplacements.Add("css-code", new CodeTagReplacer { BrushName = "css" });
                allowedTagReplacements.Add("sql-code", new CodeTagReplacer { BrushName = "sql" });
                allowedTagReplacements.Add("xml-code", new CodeTagReplacer { BrushName = "xml" });
                allowedTagReplacements.Add("javascript-code", new CodeTagReplacer { BrushName = "js" });
                _htmlFilter = new HtmlFilter(allowedTagReplacements);
                NewLineToBreakTagFilter newLineFilter = new NewLineToBreakTagFilter();
                newLineFilter.ExcludeDescendantsOfTags.Add("code");
                newLineFilter.ExcludeDescendantsOfTags.Add("c-sharp-code");
                newLineFilter.ExcludeDescendantsOfTags.Add("css-code");
                newLineFilter.ExcludeDescendantsOfTags.Add("sql-code");
                newLineFilter.ExcludeDescendantsOfTags.Add("xml-code");
                newLineFilter.ExcludeDescendantsOfTags.Add("javascript-code");
                _htmlFilter.TextNodeFilters.Add(newLineFilter);
                _htmlFilter.TextNodeFilters.Add(new DoubleEncodedAngleBracketsFilter());
            }

            return _htmlFilter.FilterHtml(html);
        }
    }
}
